package org.i0o.webplus.dao.impl.hibernate3;

import java.io.IOException;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;

/**
 * 将原来的session factory的管理分开,细化,设置hbm文件,达到分模块管理
 * 和MyLocalSessionFactoryBean相比，100%的按目录走，但是带来的问题是
 * 需要启动n个spring的applicationcontext实例，同时各个模块的文件名字必须
 * 一样，而且不能用xml结尾，模块的bean的名字也一样，这样，就对命名又 多了一条限制，当然，spring本身就不支持◎局部变量◎
 */
public class NamedMoudleHbmLocalSessionFactoryBean extends LocalSessionFactoryBean {

	/**
	 * 将原来的session factory的管理分开,细化,设置hbm文件 达到分模块管理,
	 * 
	 * @param moudleHbm
	 *            各个模块的管理服务
	 */

	public void setMappingResourceServices(Object moudleHbm) {
		String[] mappingResources = getHbm();
		super.setMappingResources(mappingResources);
	}

	public void setMappingResources(String[] mappingResources) {
		// do nothing,覆盖超类的方法,使其实效
	}

	private String[] getHbm() {
		String[] list = getFile("classpath*:modules/**/hibernate-conf/*.hbm.xml");
		return list;
	}

	private String[] getFile(String regString) {
		String[] resouceArray = null;
		try {
			ResourcePatternResolver rpr = new PathMatchingResourcePatternResolver();
			Resource[] rs = rpr.getResources(regString);
			if (rs == null) {
				return null;
			}
			resouceArray = new String[rs.length];
			int i = 0;
			for (Resource c : rs) {
				String realPath = c.getURL().getPath();

				if (realPath.contains("jar!")) {
					while (realPath.indexOf("jar!") > realPath.indexOf("modules")) {
						realPath = realPath.substring(realPath.indexOf("modules") + 7);
					}
				} else if (realPath.contains("/WEB-INF/classes/")) {
					while (realPath.indexOf("/WEB-INF/classes/") > realPath.indexOf("modules")) {
						realPath = realPath.substring(realPath.indexOf("modules") + 7);
					}
				}

				String xdpath = realPath.substring(realPath.indexOf("modules"));
				resouceArray[i] = xdpath;
				i++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return resouceArray;
	}

}